package com.luoruihang.logstatementgenerator.domain.infrastructure.http;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;

import com.alibaba.fastjson2.JSONObject;
import com.luoruihang.logstatementgenerator.domain.model.LlmRequest;
import com.luoruihang.logstatementgenerator.domain.infrastructure.database.LlmSource;
import com.luoruihang.logstatementgenerator.domain.model.llmresponseformat.GlmResponse;

import java.util.*;

public class LlmHttpUtils {

	/**
	 * 同步请求posturl：https://open.bigmodel.cn/api/paas/v4/chat/completions
	 * 异步请求posturl：https://open.bigmodel.cn/api/paas/v4/async/chat/completions
	 * 异步任务结果请求geturl：https://open.bigmodel.cn/api/paas/v4/async-result/{id}
	 */
	private static String url = LlmSource.url;
	private static String token = LlmJwtUtil.token();

	//
	public static String doPost(LlmRequest llmRequestParams) {
		Map<String, Object> params = new HashMap<>();
		params.put("model", llmRequestParams.getModel());
		params.put("messages", llmRequestParams.getMessages());
		JSONObject jsonObject = new JSONObject(params);
//		JSONObject jsonObject = JSONObject.from(llmRequestParams);// 多出了promotion
//		// 放入json的中文会直接变成乱码，响应信息中能显示中文但是还会时不时有乱码
//		// TODO 解决乱码问题
//		String jsonString=jsonObject.toString();
//
		String result=HttpRequest.post(url).contentType("application/json;charset=utf-8")
			.header(Header.AUTHORIZATION, token)
			.header(Header.CONTENT_TYPE, "application/json;charset=utf-8")
			.body(jsonObject.toString()).timeout(30000).execute().body();
		System.out.println("========================================");
		System.out.println("========================================");
		System.out.println("========================================");
		System.out.println(result);
		System.out.println("========================================");
		System.out.println("========================================");
		System.out.println("========================================");

		JSONObject.parseObject(result, GlmResponse.class);
		return result;
	}

}
